package com.cyj.springaop1.proxy.cglib;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @description: 动态代理对象测试
 * @Author C_Y_J
 * @create 2021-03-01 09:42
 **/
public class ProxyCglibTest {
    public static void main(String[] args) {
        TargetInterfaceImpl targetInterface = new TargetInterfaceImpl();
        Advice advice = new Advice();
        //1、创建增强器
        Enhancer enhancer = new Enhancer();
        //2、设置父类（其实就是目标类)
        enhancer.setSuperclass(TargetInterfaceImpl.class);
        //3、设置回调 setCallback()需要的参数是Callback接口，我们用Callback接口下的MethodInterceptor子接口
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                //前置方法
                advice.before();
                //目标方法
                method.invoke(targetInterface, args);
                //后置方法
                advice.afterReturning();
                return null;
            }
        });
        //4、创建代理对象
        TargetInterfaceImpl proxy = (TargetInterfaceImpl) enhancer.create();
        //测试
        proxy.save();
    }
}
